package com.LeeCode;

import java.util.ArrayList;
import java.util.List;

/**
 * 括号回溯
 */

public class Code022 {
    public static void main(String[] args) {
        int n = 3;
        System.out.println(new Code022().generateParenthesis(n));
    }

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        backtrace(res, new StringBuilder(), 0, 0, n);
        return res;
    }

    // 本质上是在搜索树上进行遍历，需要确定当前搜索树节点的后继节点有哪些
    public void backtrace(List<String> res, StringBuilder cur, int left, int right, int max) {
        if (cur.length() == max * 2) {
            res.add(cur.toString());
        }
        if (left < max) { // 添加左括号
            cur.append('(');
            backtrace(res, cur, left + 1, right, max);
            cur.deleteCharAt(cur.length() - 1);
        }
        if (right < left) { // 右括号数量少于左括号时才可以添加
            cur.append(')');
            backtrace(res, cur, left, right + 1, max);
            cur.deleteCharAt(cur.length() - 1);
        }
    }
}
